package com.lxl.xm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.lxl.xm.common.BaseResponse;
import com.lxl.xm.common.ErrorCode;
import com.lxl.xm.common.ResultUtils;
import com.lxl.xm.exception.BusinessException;
import com.lxl.xm.model.dto.advertiser.AdvertiserAddRequest;
import com.lxl.xm.model.entity.Advertiser;
import com.lxl.xm.service.AdvertiserService;
import com.lxl.xm.model.vo.AdvertiserVO;
import com.lxl.xm.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/advertiser")
@Slf4j
public class AdvertiserController {

    @Resource
    AdvertiserService advertiserService;
    @Autowired
    private MailService mailService;

    /**
     * 广告商分页查询
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/page")
    public BaseResponse<Page<Advertiser>> getAdvertisers(@RequestParam(name = "page",defaultValue = "1")int current,
                                           @RequestParam(name = "size",defaultValue = "10")int size){
        Page<Advertiser> page = advertiserService.getAdvertiserPage(current,size);
        return ResultUtils.success(page);
    }

    /**
     *
     * 根据id获取广告商信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public BaseResponse<Advertiser> getAdvertiserById(@PathVariable Long id){
        Advertiser advertiser = advertiserService.getAdvertiserById(id);
        return ResultUtils.success(advertiser);
    }

    /**
     * 模糊查询广告商信息（广告商名称/邮箱/电话）
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<Page<Advertiser>> searchAdvertisers(@RequestParam String keyword, @RequestParam int page, @RequestParam int size) {
        Page<Advertiser> advertisers = advertiserService.searchAdvertisers(keyword, page, size);
        return ResultUtils.success(advertisers);
    }

    /**
     * 新增广告商
     * @param advertiser
     * @return
     */
    @PostMapping("/create")
    public BaseResponse<?>createAdvertiser(@RequestBody Advertiser advertiser){
        boolean isCreate = advertiserService.createAdvertiser(advertiser);
        if(isCreate){
            return ResultUtils.success(true);
        }
        else{
            return ResultUtils.error(500,"创建失败");
        }
    }

    /**
     * 删除广告商
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public BaseResponse<?>deleteAdvertiser(@PathVariable Long id){
        boolean isDeleted = advertiserService.deleteAdvertiserById(id);
        if(isDeleted){
            return ResultUtils.success(true);
        }
        else{
            return ResultUtils.error(500,"未找到广告商");
        }
    }

    /**
     * 更新广告商信息
     * @param advertiser
     * @return
     */
    @PutMapping("/update/{id}")
    public BaseResponse<?>updateAdvertiser(@RequestBody Advertiser advertiser){
        boolean isUpdated = advertiserService.updateAdvertiser(advertiser);
        if(isUpdated){
            return ResultUtils.success(true);
        }
        else{
            return ResultUtils.error(500,"更新失败");
        }
    }

    /**
     * 获取待审核商家信息
     * @return
     */
    @GetMapping("/pending")
    public BaseResponse<List<Advertiser>> getPendingAdvertisers(){
        List<Advertiser>pendingAdvertiers = advertiserService.getPendingAdvertisers();
        return ResultUtils.success(pendingAdvertiers);
    }

    /**
     * 审核商家
     * @param id 商家id
     * @param status 审核状态
     * @param notes 备注
     * @return
     */
    @PostMapping("/review/{id}")
    public BaseResponse<String> reviewAdvertiser(@PathVariable("id")Long id,
                                                   @RequestParam("status")Integer status,// 审核状态：1通过，2拒绝
                                                   @RequestParam("notes")String notes){
        advertiserService.reviewAdvertiser(id,status,notes);
        return ResultUtils.success("审核成功");
    }

    @PostMapping("/sendEmail")
    @ResponseBody
    public BaseResponse<String> sendEmail(@RequestParam String email, HttpSession httpSession){
        try {
            mailService.sendMimeMail(email, httpSession);
            return ResultUtils.success("验证码发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtils.error(-1,"验证码发送失败！");
        }
    }

    @PostMapping("/regist")
    @ResponseBody
    public BaseResponse<String> regist(@RequestBody AdvertiserVO advertiserVO, HttpSession session){
//        try {
//            mailService.registered(advertiserVO, session);
//            return ResultUtils.success("注册成功");
//        }catch (Exception e){
//            e.printStackTrace();
//            return ResultUtils.error(-2,"注册失败！");
//        }
        try{
            boolean isRegistered = mailService.registered(advertiserVO,session);
            if(isRegistered){
                return ResultUtils.success("注册成功");
            }else{
                return ResultUtils.error(-2,"注册失败");
            }
        }catch (BusinessException e){
            e.printStackTrace();
            return ResultUtils.error(e.getCode(),e.getMessage());
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public BaseResponse<String> login(@RequestParam String email,@RequestParam String password){
        try{
        mailService.loginIn(email,password);
        return ResultUtils.success("登录成功");
        }catch (BusinessException e){
            e.printStackTrace();
            return ResultUtils.error(e.getCode(),e.getMessage());
        }
    }

    @GetMapping("total")
    public BaseResponse<Integer> count(){
        Integer count = advertiserService.getCount();
        return ResultUtils.success(count);
    }



//
//    @PostMapping("register")
//    public BaseResponse<Boolean> advertiserRegister(){
//        return false;
//    }

    /**
     * 添加商家
     *
     * @param advertiserAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addAdvertiser(@RequestBody AdvertiserAddRequest advertiserAddRequest, HttpServletRequest request) {
        if (advertiserAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Advertiser advertiser = new Advertiser();
        BeanUtils.copyProperties(advertiserAddRequest, advertiser);
        boolean result = advertiserService.save(advertiser);
        // 抛异常
        if (!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"添加失败");
        }
        long newStudentId = advertiser.getId();
        // 返回用户的id
        return ResultUtils.success(newStudentId);
    }

/*

    */
/**
     * 商家登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     *//*

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }
*/



}
